"use strict"

var log 	= 	console.log,										//env variables
	http 	= 	require('http'),
	GET 	=	require("./php-get.js"),
	DB		=	require("./DB-storage.js"),
	cleaner = 	require("./game-cleaner.js")

cleaner.start()														//start the game cleaner timer loop


var loc = "127.0.0.1", port = 1337
http.createServer(function (req, res) {								//main server loop
	req.content = ""
	req.addListener("data", function(chunk) {
		req.content += chunk
	})
	req.addListener("end", function() {
		handlePOST(req, res)
	})
}).listen(port, loc)


var handlePOST = function(req, res) {
	//set some crap to allow chrome to do CORS
	var responseHead = {
		'Content-Type': 'text/plain',
		'Access-Control-Allow-Origin': '*',
		"Access-Control-Allow-Credentials": "true",
		"Access-Control-Allow-Methods": "OPTIONS, GET, POST",
		"Access-Control-Allow-Headers": "Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control"
	}
	var statusCode = 200, response = ""
	
	var cTime = new Date().getTime()								//current time of script execution. bound to be useful
	var data = GET.parse(req.content)								//turn the POST into an array of vars
	
	switch (data.type) {											//select by request type
		case "sendMove":											//save sent move
			//res.write(data.payload + "\n")
			DB.storeMove(data.payload)								//save it (error check this?)
			response += "sendMove: successfully received \n"		//all ok!
			break
			
		case "getMove":
			var move = DB.retrieveMove(data.payload)
			if (move === false) {									//false signifies no game exists
				statusCode = 204
				//response += "getMove: move could not be retrieved or does not exist \n"
			} else {
				response += move
			}
			break
			
		case "gamesList":
			var gamesList = DB.gamesList()
			response += JSON.stringify(gamesList)
			break
		
		case "checkGameStatus":
			var game = DB.retrieveGame(data.payload)				//get game from the filesystem
			
			game = JSON.parse(game)
			game.lastUpdated = cTime
			game = JSON.stringify(game)								//update last access time
			DB.storeGame(game)										//save last access time
			
			response += game										//return current game state
			break
			
		case "joinGame":
			var game = DB.retrieveGame(data.payload)				//retrieve game from filesystem
			if (game === false) {
				statusCode = 404
				response += "joinGame: game could not be retrieved or does not exist \n"
				break
			}
			
			game = JSON.parse(game)									//get the game and payload as json
			var json = JSON.parse(data.payload)
			if (game.players.length === 2) {						//only 2 players per game
				statusCode = 400
				response += "joinGame: game is already full \n"
				break
			} else if (game.players[0] === json.playerName) {		//players must have unique names
				statusCode = 400
				response += "joinGame: both opponents cannot have the same name \n"
				break
			}
			game.players.push(json.playerName)						//add player to game
			game.lastUpdated = cTime
			game = JSON.stringify(game)
			DB.storeGame(game)
			
			response += game										//return game details to player
			break
		
		case "createGame":
			var game = JSON.parse(data.payload)
			var gameId = game.playerName + (Math.random()+"").substr(1)
			
			var newGame = {											//create new game (temp location?)
				gameId: gameId,
				created: cTime,
				lastUpdated: cTime,
				players: [ game.playerName ],
				winner: 0
			}

			newGame = JSON.stringify(newGame)						//save the new game
			DB.storeGame(newGame)
			
			response += newGame										//return it
			break
				
		default:
			statusCode = 400										//Bad Request
			response += "'type' was not recognised \n"
	}
	
	res.writeHead(statusCode, responseHead)
	if (response)  res.write(response)

	//res.write(JSON.stringify(data) + "\n")
	//res.write(req.method + "\n") //check method?
	
	res.end()
}


log('Server running at http://' + loc + ':' + port + '/')
